//
//  AIADViewController.m
//  aixianfeng
//
//  Created by 李江波 on 2016/12/24.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "AIADViewController.h"
#import "LEEHTTPManager.h"
#import "AIMainTabController.h"


@interface AIADViewController ()

@property(nonatomic ,strong) UIImageView *imageView;

@end

@implementation AIADViewController{

    NSTimer *_timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    [self setupUI];
}
-(void)loadData{
    
    NSString *URLstr = @"http://iosapi.itcast.cn/loveBeen/ad.json.php";
    NSDictionary *parameter = @{@"call" : @(7)};
    [[LEEHTTPManager share] request:POST UrlString:URLstr parameters:parameter finshed:^(NSDictionary *responseObject, NSError *error) {
       
        if (error != nil) {
            
            return ;
        }
        
//        NSLog(@"%@",responseObject);
        NSString *imageName = responseObject[@"data"][@"img_name"];
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imageName] options:2 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
           
              [[NSUserDefaults standardUserDefaults] setObject:imageName forKey:USERDEFAULTS];
            //在用户清除缓存的时候也要设置偏好设置不然图片没了，pilst还在啊！！！！
            
        }];
        
    }];
    
}

static NSInteger num = 3;
-(void)setupUI{
    
    NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:USERDEFAULTS];
    self.imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    self.imageView.image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:url];
    
    [self.view addSubview:self.imageView];
    
    UIButton *time = [UIButton buttonWithType:0];
    [self.view addSubview:time];
    
    time.backgroundColor = [UIColor lightGrayColor];
    [time setTitle:@"倒计时:3S" forState:UIControlStateNormal];
    [time addTarget:self action:@selector(moveToTabVc) forControlEvents:UIControlEventTouchUpInside];
    [time mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.view).offset(20);
        make.left.equalTo(self.view.mas_right).offset(-110);
        make.width.offset(90);
    }];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
       
        num --;
        [time setTitle:[NSString stringWithFormat:@"倒计时:%zdS",num] forState:UIControlStateNormal];
        if (num == 0) {
            
            [self moveToTabVc];
        }
        
    }];
}

-(void)moveToTabVc{

    [UIApplication sharedApplication].keyWindow.rootViewController = [[AIMainTabController alloc]init];
}

-(void)dealloc{

    [_timer invalidate];
}


@end
